package com.example.oj.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.oj.entity.Question;
import com.example.oj.entity.Submit;
import com.example.oj.service.QuestionService;
import com.example.oj.service.SubmitService;
import com.example.ojcommon.common.BaseResponse;
import com.example.ojcommon.common.ErrorCode;
import com.example.ojcommon.common.ResultUtils;
import com.example.ojcommon.exception.BusinessException;
import com.example.ojcommon.exception.ThrowUtils;
import com.example.oj.entity.dto.submit.SubmitAddRequest;
import com.example.oj.entity.dto.submit.SubmitQueryRequest;
import com.example.oj.entity.vo.SubmitVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 题目提交接口
 */
@RestController
@RequestMapping("/submit")
@Slf4j
public class SubmitController {

    @Resource
    private SubmitService submitService;

    @Resource
    private QuestionService questionService;

    /**
     * 提交题目
     *
     * @param submitAddRequest
     * @param request
     * @return resultNum
     */
    @PostMapping("/add")
    public BaseResponse<Long> submitQuestion(@RequestBody SubmitAddRequest submitAddRequest,
                                             HttpServletRequest request) {
        if (submitAddRequest == null || submitAddRequest.getQuestionId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        submitService.doSubmitQuestion(submitAddRequest,request);
        return ResultUtils.success(1L);
    }

    /**
     * 查看题目提交记录，需要登录
     *
     * @param submitQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    public BaseResponse<Page<SubmitVO>> listSubmitById(@RequestBody SubmitQueryRequest submitQueryRequest,
                                                       HttpServletRequest request) {
        long current = submitQueryRequest.getCurrent();
        long size = submitQueryRequest.getPageSize();

        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<SubmitVO> submitVOPage = submitService.listPageQuestionVO(submitQueryRequest);
        return ResultUtils.success(submitVOPage);
    }

    @PostMapping("/getById")
    public BaseResponse<SubmitVO> getSubmitVOById(Long id,HttpServletRequest request){
        Submit submit = submitService.getById(id);
        SubmitVO submitVO = submitService.getSubmitVO(submit);
        return ResultUtils.success(submitVO);
    }

}
